package com.CameraCropTest;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class CameraCropTest extends Activity {

	private Uri mImageCaptureUri;

	private final int REQ_IMAGE_CAMERA = 1001;
	private final int REQ_IMAGE_CAMERA2 = 1002;
	private final int REQ_IMAGE_CAMERA3 = 1003;
	private final int REQ_IMAGE_CAMERA4 = 1004;

	private final int REQ_IMAGE_GALLERY1 = 1005;
	private final int REQ_IMAGE_GALLERY2 = 1006;
	private final int REQ_IMAGE_GALLERY3 = 1007;

	private CameraCropTest mContext;

	private ImageView mPreView;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mContext = this;
		LinearLayout main = (LinearLayout) findViewById(R.id.main);
		mPreView = (ImageView) findViewById(R.id.image_preview);

		setButton(main, "카메라에서 가져오기").setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				getImageformCamera1();
			}
		});
		setButton(main, "카메라에서 가져오기 지정된곳에 저장").setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				getImageformCamera2();
			}
		});
		setButton(main, "카메라에서 가져오기 crop").setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				getImageformCamera3();
			}
		});
		setButton(main, "카메라에서 가져오기 지정된곳에 저장 crop").setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				getImageformCamera4();
			}
		});

		setButton(main, "겔러리").setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				getImageformGallery1();
			}
		});

		setButton(main, "겔러리 외부저장").setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				getImageformGallery2();
			}
		});

		setButton(main, "겔러리 crop").setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				getImageformGallery3();
			}
		});
	}
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != Activity.RESULT_OK)
			return;
		Log.l(data, data != null ? data.getData() : "", data != null ? data.getExtras() : "");
		switch (requestCode) {
			case REQ_IMAGE_CAMERA :
				REQ_IMAGE_CAMERA1(data);
				break;
			case REQ_IMAGE_CAMERA2 :
				REQ_IMAGE_CAMERA2(data);
				break;
			case REQ_IMAGE_CAMERA3 :
				REQ_IMAGE_CAMERA3(data);
				break;
			case REQ_IMAGE_CAMERA4 :
				REQ_IMAGE_CAMERA4(data);
				break;
			case REQ_IMAGE_GALLERY1 :
				REQ_IMAGE_GALLERY1(data);
				break;
			case REQ_IMAGE_GALLERY2 :
				REQ_IMAGE_GALLERY2(data);
				break;
			case REQ_IMAGE_GALLERY3 :
				REQ_IMAGE_GALLERY3(data);
				break;

		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private Button setButton(LinearLayout main, String string) {
		Button button = new Button(mContext);
		button.setText(string);
		main.addView(button);
		return button;
	}

	protected void getImageformCamera1() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(intent, REQ_IMAGE_CAMERA);
	}
	private void REQ_IMAGE_CAMERA1(Intent data) {
		Bitmap bitmap = (Bitmap) data.getParcelableExtra("data");
		if (bitmap != null) {
			mPreView.setImageBitmap(bitmap);
		}
	}

	protected void getImageformCamera2() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), String.valueOf(System.currentTimeMillis() + "_picture.jpg")));
		intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
		intent.putExtra("return-data", true);

		startActivityForResult(intent, REQ_IMAGE_CAMERA2);
	}
	private void REQ_IMAGE_CAMERA2(Intent data) {
		mPreView.setImageURI(mImageCaptureUri);
	}

	protected void getImageformCamera3() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra("crop", "true");
		startActivityForResult(intent, REQ_IMAGE_CAMERA3);
	}
	private void REQ_IMAGE_CAMERA3(Intent data) {
		Bitmap bitmap = (Bitmap) data.getParcelableExtra("data");
		if (bitmap != null) {
			mPreView.setImageBitmap(bitmap);
		}
	}

	protected void getImageformCamera4() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), String.valueOf(System.currentTimeMillis() + "_picture.jpg")));
		intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
		intent.putExtra("return-data", true);
		intent.putExtra("crop", "true");
		startActivityForResult(intent, REQ_IMAGE_CAMERA4);
	}
	private void REQ_IMAGE_CAMERA4(Intent data) {
		// mImageCaptureUri == Uri.parse(data.getAction())
		mPreView.setImageURI(Uri.parse(data.getAction()));
		// or
		// mPreView.setImageURI(mImageCaptureUri);
	}

	protected void getImageformGallery1() {
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStore.Images.Media.CONTENT_TYPE);
		// or
		// intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		// or
		// intent.setType(MediaStore.Images.Media.CONTENT_TYPE);
		startActivityForResult(intent, REQ_IMAGE_GALLERY1);
	}
	private void REQ_IMAGE_GALLERY1(Intent data) {
		// java.lang.OutOfMemoryError: bitmap size exceeds VM budget
		mPreView.setImageURI(data.getData());
	}

	protected void getImageformGallery2() {
		Intent intent = new Intent(Intent.ACTION_PICK);

		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStore.Images.Media.CONTENT_TYPE);
		mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), String.valueOf(System.currentTimeMillis() + "_picture.jpg")));
		intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
		intent.putExtra("return-data", true);

		startActivityForResult(intent, REQ_IMAGE_GALLERY2);
	}
	private void REQ_IMAGE_GALLERY2(Intent data) {
		// java.lang.OutOfMemoryError: bitmap size exceeds VM budget
		// mImageCaptureUri == Uri.parse(data.getAction())
		mPreView.setImageURI(Uri.parse(data.getAction()));
		// or
		// mPreView.setImageURI(mImageCaptureUri);
	}

	protected void getImageformGallery3() {
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStore.Images.Media.CONTENT_TYPE);

		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 200);
		intent.putExtra("outputY", 200);

		startActivityForResult(intent, REQ_IMAGE_GALLERY3);
	}
	private void REQ_IMAGE_GALLERY3(Intent data) {
		// java.lang.OutOfMemoryError: bitmap size exceeds VM budget
		mPreView.setImageURI(data.getData());
	}

	private void crop(Uri uri) {

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setData(uri);
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 200);
		intent.putExtra("outputY", 200);
		// intent.putExtra("noFaceDetection", true);

		try {
			intent.putExtra("return-data", true);
			startActivityForResult(intent, REQ_IMAGE_GALLERY1);
		} catch (ActivityNotFoundException e1) {

		}

	}

	class MediaScannerFile implements MediaScannerConnectionClient {
		private MediaScannerConnection msc = null;
		String path;

		MediaScannerFile(String path) {
			this.path = path;
			msc = new MediaScannerConnection(getApplicationContext(), this);
			msc.connect();
		}
//		MediaScannerFile(Uri uri) {
//			this.path = path;
//			msc = new MediaScannerConnection(getApplicationContext(), this);
//			msc.connect();
//		}

		public void onMediaScannerConnected() {
			msc.scanFile(path, null);
		}

		public void onScanCompleted(String path, Uri uri) {
			msc.disconnect();
		}

	}

	void deletefile() {
		try {
			File f = new File(mImageCaptureUri.getPath());
			if (f.exists()) {
				f.delete();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void saveLocalFile(Bitmap bm) {
		try {
			File f = new File(getFilesDir(), "image.jpeg");
			FileOutputStream fos = new FileOutputStream(f);
			bm.compress(Bitmap.CompressFormat.JPEG, 100, fos);
			fos.flush();
			fos.close();
			Log.e("image files", getFilesDir().getAbsolutePath() + "/" + f.getName());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Bitmap uri2bitmap(Bitmap bm) {
		try {
			return Images.Media.getBitmap(mContext.getContentResolver(), mImageCaptureUri);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	// public void scanningMedia(final String path) {
	// MediaScannerConnectionClient mediaScannerClient = new MediaScannerConnectionClient() {
	// private MediaScannerConnection msc = null;
	// {
	// msc = new MediaScannerConnection(getApplicationContext(), this);
	// msc.connect();
	// }
	//
	// public void onMediaScannerConnected() {
	// msc.scanFile(path, null);
	// }
	//
	// public void onScanCompleted(String path, Uri uri) {
	// msc.disconnect();
	// }
	// };
	// }

}